package com.app.android.coliy.manager;

import android.content.Context;
import android.text.TextUtils;

import com.app.android.coliy.constant.SPConstants;
import com.app.android.coliy.interface_.OkHttpCallBack;
import com.app.android.coliy.responce.BaseResponce;
import com.app.android.coliy.tool.Log;
import com.app.android.coliy.tool.SPUtil;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.AbsCallback;
import com.lzy.okgo.model.HttpMethod;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.BodyRequest;
import com.lzy.okgo.request.base.Request;

import org.json.JSONObject;

import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/8/13.
 */

public class OkHttpManager {

    /**
     * okHttp请求， 外部调用
     *
     * @param context       上下文，用于取消请求
     * @param methed        请求类型 (HttpMethod.POST/HttpMethod.GET)
     * @param url           请求地址
     * @param requestBody   post方式 放入请求体的参数
     * @param responseClass 返回responce类型 （自动解析json）
     * @param callBack      回调对象
     */
    public static void okHttpRequest(Context context, HttpMethod methed, String url, Map<String, String> requestBody, Class<? extends BaseResponce> responseClass, OkHttpCallBack callBack) {
        executeByOkHttp(methed, context, url, requestBody, null, responseClass, callBack);
    }
//
//    //文件上传
//    public static void okHttpFileUpload(Context context, HttpMethod methed, String url, Map<String, String> requestBody, String filekeyName, List<File> files, Class<? extends BaseResponce> responseClass, OkHttpCallBack callBack) {
//        //headers参数
//        Map<String, String> headers = null;
//        headers = new HashMap<>();
//        if (UserManager.getUserInfo(context) != null) {
//            headers = new HashMap<>();
//            headers.put("token", UserManager.getUserInfo(context).token);
//        }
//        uploadByOkhttp(context, url, headers, responseClass, files, callBack);
//    }

    private static void uploadByOkhttp(final Context context, final String url, Map<String, String> headers, final Class<? extends BaseResponce> responseClass, List<File> files, final OkHttpCallBack callBack) {
        BodyRequest request = OkGo.post(url);
        //添加headers
        if (headers != null && headers.size() > 0) {
            for (String key : headers.keySet()) {
                String value = headers.get(key);
                request.getHeaders().put(key, value);
            }
        }
        if (files != null) {
            request.addFileParams("file", files);
        }
        request.execute(new AbsCallback<BaseResponce>() {
            @Override
            public BaseResponce convertResponse(okhttp3.Response response) throws Throwable {
                //子线程
                BaseResponce object = null;
                try {
                    String s = response.body().string();
                    Log.i("result:" + s);
                    if (responseClass != null) {
                        object = new Gson().fromJson(s, responseClass);
                    }
//                        else {
//                            object = new BaseResponce();
//                            object.code = "10000";
//                        }
//                        object.result = s;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return object;
            }

            @Override
            public void onSuccess(Response<BaseResponce> response) {
                if (callBack == null) return;
                BaseResponce baseResponce = response.body();
                //UI线程
                if (baseResponce == null)  //数据解析失败
                {
                    callBack.onFailure(baseResponce);
                } else {           //数据解析成功
                    callBack.onSuccess(baseResponce);
//                        if ("200".equals(baseResponce.code)) {
//                            callBack.onSuccess(baseResponce);
//                        } else {
//                            callBack.onFailure(baseResponce);
//                        }
                }
            }

            @Override
            public void onError(Response<BaseResponce> response) {
                super.onError(response);
                if (callBack != null) {
                    callBack.onFailure(null);
                }
            }
        });

    }


    private static void executeByOkHttp(HttpMethod methed, final Context context, final String url, Map<String, String> requestBody, Map<String, String> headers, final Class<? extends BaseResponce> responseClass, final OkHttpCallBack callBack) {
        try {
            Request request = null;
            //添加body
            if (HttpMethod.POST == methed) {
                JSONObject jsonObject = new JSONObject(requestBody);
                request = OkGo.post(url).tag(context).upJson(jsonObject);
            } else {
                request = OkGo.get(url).tag(context);
            }

            //添加headers
            if (headers != null && headers.size() > 0) {
                for (String key : headers.keySet()) {
                    String value = headers.get(key);
                    request.getHeaders().put(key, value);
                }
            }

            String requestCookie = SPUtil.getStringValue(context, SPConstants.Cookie, "");
            if (!TextUtils.isEmpty(requestCookie)) {
                request.getHeaders().put("Cookie", requestCookie);
            }

            request.execute(new AbsCallback<BaseResponce>() {
                @Override
                public BaseResponce convertResponse(okhttp3.Response response) throws Throwable {
                    //子线程
                    BaseResponce object = null;
                    String s = response.body().string();

                    if (responseClass != null) {
                        try {
                            object = new Gson().fromJson(s, responseClass);
                        } catch (Exception e) {
                            object = new Gson().fromJson(s, BaseResponce.class);
                        }
                    } else {
                        object = new BaseResponce();
//                        BaseResponce_Data data = new BaseResponce_Data();
//                        data.code = BaseResponce.Status_Success;
//                        data.result = s;
                    }
                    object.result = s;
                    return object;
                }

                @Override
                public void onSuccess(Response<BaseResponce> response) {
                    if (callBack == null) return;
                    BaseResponce baseResponce = response.body();
                    //UI线程
                    if (baseResponce == null)  //数据解析失败
                    {
                        callBack.onFailure(baseResponce);
                    } else {           //数据解析成功
//                        callBack.onSuccess(baseResponce);
                        callBack.onSuccess(baseResponce);
                        String cookie = response.headers().get("Set-Cookie");
                        SPUtil.putValue(context, SPConstants.Cookie, cookie);
                        Log.i("cookie:" + cookie);
                    }
                }

                @Override
                public void onError(Response<BaseResponce> response) {
                    super.onError(response);
                    if (callBack != null) {
                        callBack.onFailure(null);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            if (callBack != null) {
                callBack.onFailure(null);
            }
        }
    }

}
